package com.gzz.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
// 工具类
public class JWTUtils {
	private static final long EXPIRE_TIME = 360 * 60 * 1000;
	// 私钥
	private static final String TOKEN_SECRET = "zjc-gjy-zwq";

	public static String getToken(Long id) {
		try {
			// 设置过期时间
			Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
			// 私钥和加密算法
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			// 设置头部信息
			Map<String, Object> header = new HashMap<>(2);
			header.put("Type", "Jwt");
			header.put("alg", "HS256");
			// 返回token字符串
			return JWT.create()
					.withHeader(header)
					.withClaim("id", id)
					//.withExpiresAt(date)
					.sign(algorithm);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Long parseToken(String token){
		try {
			Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
			JWTVerifier verifier = JWT.require(algorithm).build();
			DecodedJWT jwt = verifier.verify(token);
			return jwt.getClaim("id").asLong();
		} catch (Exception e){
			return 0L;
		}
	}

}
